var util = require('../../utils/util.js')
var utilMd5 = require('../../utils/md5.js');
var app = getApp();
var wxAuthFail = true;
// pages/order-confirm/order-confirm.js
var payType = 1; //1:立即支付; 2:提后付款
var isTest=false;
var progressNum =0; //定义一个初始值0
var jindutiaoShow = false;
var quedingShow = false;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    tc:1,
    util: util,

    userinfo:{},
    cuid:0,
    token: '',
    openid: '',

    choosenum:0,

    wx_address: '',
    address: {},
    ps_address:{},
    zt_address:{},

    goodsinfoArr:[],
    kucun:0,
    oneprice:0,

    totalPrice:0,
    yunfei: 0,

    my_cion: 68,//满 免运费
    set_yunfei: 5,// 运费
    
    user_jifen: 0,
    use_jf: 0,
    add_jf: 0,

    liuyan:'',

    textarea_w: 300,

    hour: 8,

    hasZitiAddr: false,//是否有自提地址
    ziti: false,//是否自提

    colorSet: '',

    jindutiaoTest :'正在处理中,请稍候',

    myhao:'',

    roomtitle:'',
    roomimage:'',
    agree:true
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var tc = app.get_tc();
    var that = this;
    that.setData({
      tc: tc,
      // jindutiaoTest: tc == 1 ? '正在派單中,請稍候' : '正在派单中,请稍候',
      choosenum : options.choosenum,
      roomtitle: options.roomtitle,
      roomimage: options.roomimage,
      brtime: options.brtime,
      btype: options.btype,
      brtimeStr: that.getDateStr(parseInt(options.brtime)-1)
    });
    console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", options.roomtitle);
    console.log("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", options.roomimage);
    var titlename = tc == 1 ? '確認訂單' : '确认订单';
    wx.setNavigationBarTitle({
      title: titlename,
    })
    // var result = that.data.tc == 1 ? '購買成功' : '购买成功';
    // that.jindutiao(result);
    // payType = options.payType == "2" ? 2 : 1;
    payType = options.payType == "2" ? 2 : 1;
    wx.showLoading({
      title: 'loading...',
      mask: 'true'
    })
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          textarea_w: res.windowWidth - 32,
        })
      },
    })
    //获取颜色配置
    app.getColorSetData(function (color) {
      that.setData({
        colorSet: color
      })
      that.resetNavColor();
    });

    //获取关于等信息
    app.getAllAbout('contact', function (res) {
      that.setData({
        contact_phone: res
      })
    });

    
    //读取运费设置信息 
    this.getYunfeiSet();

    this.getLoginInfo(); 
 
    
    
    

    //可控制每天的可下单时间段
    var date = new Date();
    var hour = date.getHours();

    var g_infoArr = JSON.parse(options.goodsArr);
    console.log("商品信息：", g_infoArr);
    this.setData({
      goodsinfoArr: g_infoArr,
      cashPledge: parseInt(g_infoArr[0].yunfei),
      hour: hour,
      currentObjStart:wx.getStorageSync("dateStartObj"),
      currentObjEnd:wx.getStorageSync("dateEndObj"),
      dateStart: that.getMDstring(wx.getStorageSync("dateStartObj")),
      dateEnd: that.getMDstring(wx.getStorageSync("dateEndObj"))
    })
    this.getInterval()

 
    //获取自提地址
    this.getZitiAddr();

    
  },



  

  getLoginInfo: function () {
    var that = this;
    app.LoginUserInfo(function (res) {
      console.log("mine login:", res);
      wxAuthFail = res == -1;//用户拒绝授权
      if (wxAuthFail) {
        return;
      }
      that.setData({
        cuid: res.uid,
        openid: res.wxsmall_openid,
        token: res.token
      });
      that.getJifen();//获取积分
      if(util.orgid != '12545'){
        that.getAddress();//获取地址
      }
    });
  },

  //重新读取 登录用户信息
  reGetUserInfo: function (e) {
    var that = this;
    console.log("reGetUserInfo: ", e);
    if (e == 1) {
      that.getLoginInfo();
    }
  },

  //获取自提地址
  getZitiAddr: function(){
    var that = this;
    //自提点地址
    util.api({
      data: {
        publickey: util.publiccode,
        ac: "getpeisong",
        uid: util.orgid
      },
      success: function (responseData) {
        var data = responseData.data;
        console.log("自提地址：", data);
        if (data && data.length > 0) {
          that.setData({
            hasZitiAddr: true
          });
        }
        wx.hideLoading();
        if (util.orgid=='13078'&&that.data.ziti== true) {
          that.setData({
            address: that.data.zt_address
          })
          console.log('that.data.zt_address：', that.data.zt_address);

        }
      }
    });
  },

  getJifen:function(){
    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "getusersource",
        "uid": that.data.cuid
      },
      success: function (responseData) {
        console.log("积分", responseData.data)
        that.setData({
          user_jifen: responseData.data.source
        })
      }
    });
  },
  jifenInput:function(e){
    this.setData({
      use_jf: e.detail.value
    })
    this.calTotalPrice();
  },

  radioChange:function(e){
    var that = this;
    console.log('radio发生change事件，携带value值为：', e.detail.value);
    if(e.detail.value == 'zt'){
      this.setData({
        ziti: true,
        address: that.data.zt_address
      })
      console.log('that.data.zt_address：', that.data.zt_address);
    } else {
      this.setData({
        ziti: false,
        address: that.data.ps_address
      })
      console.log('that.data.ps_address：', that.data.ps_address);
    }
    this.calTotalPrice();
  },

  getAddress:function(){

    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "getaddress",
        "uid": that.data.cuid
      },
      success: function (responseData) {
        console.log("收货地址：", responseData.data)
        if (responseData.data.length > 0) {
          for(var i = 1; i < responseData.data.length; i++){
            var addrItem = responseData.data[i];
            that.delAddress(addrItem.id);
          }
          that.setData({
            address: responseData.data[0],
            ps_address: responseData.data[0]
          });
        } else {
          //读取微信收货地址
          if (util.orgid != '16708') {
            that.getWxAddress();

          }
        }
      }
    });
  },

  inputNameBlur: function (e) {
    console.log("名字= " + e.detail.value);
    var addr = this.data.address;
    addr.name = e.detail.value;
    if (!this.data.ziti) {
      this.setData({
        address: addr,
        ps_address: addr
      })

    }else{
      this.setData({
        address: addr,
        zt_address: addr
      })
    }
  },

  inputPhoneBlur: function (e) {
    console.log("联系电话= " + e.detail.value);
    var addr = this.data.address;
    addr.phone = e.detail.value;
    if (!this.data.ziti) {
      this.setData({
        address: addr,
        // zt_address: addr
      })

    }
  },
  
  inputIdcardBlur: function (e) {
    console.log("证件号码= " + e.detail.value);
    var addr = this.data.address;
    addr.idcard = e.detail.value;
    if (!this.data.ziti) {
      this.setData({
        address: addr,
        // zt_address: addr
      })

    }
  },

  inputAddressBlur: function (e) {
    console.log("地址= " + e.detail.value);
    var addr = this.data.address;
    addr.address = '';
    if (!this.data.ziti) {
      this.setData({
        address: addr,
        // zt_address: addr
      })

    }
  },

  setPSAddress: function (psd_addr) {
    var addr = this.data.address;
    addr.psd_phone = psd_addr.phone;
    addr.address = psd_addr.address + '-' + psd_addr.name;
    if (!this.data.ziti) {
      this.setData({
        address: addr,
        ps_address: addr
      })

    }else{
      this.setData({
        address: addr,
        zt_address: addr
      })
    }
  },

 

  //处理总价
  calTotalPrice: function () {
    var that=this;
    var allData = this.data.goodsinfoArr;
    console.log("allData===", allData);
    var allGoodPrice = 0;
    var cangetJifen = 0; // 本次购买能得到的积分
    for (var i = 0; i < allData.length; i++) {
      if (allData[i].sel) {
        if (allData[i].attribute) {
          var attribute = allData[i].attribute;
          for (var j = 0; j < attribute.length; j++) {
            if (attribute[j].attributePrice) {
              allGoodPrice += parseInt(attribute[j].attributePrice) * 100;
            }
          }
        }
        allGoodPrice += allData[i].price * allData[i].buycount;
        // Yunfei += parseInt(allData[i].yunfei) * 100;
        cangetJifen += allData[i].source * allData[i].buycount;
      }
    }

    var yunfei = this.data.set_yunfei;
    if (allGoodPrice / 100 >= this.data.my_cion) {
      yunfei = 0;
    }
    allGoodPrice += (yunfei * 100);
    //积分抵扣
    if(this.data.use_jf > 0){
      allGoodPrice -= this.data.use_jf;
    }
    if (!this.data.ziti){
      var allPrice = (allGoodPrice / 100.0).toFixed(2);
    }
    if ((this.data.ziti)){  
      var allPrice = (allGoodPrice / 100.0).toFixed(2)- yunfei;
    }
    if(util.orgid==18535){
      
      if (this.data.btype != 3){

        allPrice = allPrice * this.data.interval;
      } else if (this.data.btype == 3){
        allPrice = allPrice
      }
    }
    this.setData({
      totalPrice: allPrice,
      totalPriceAddCashPledge: allPrice+that.data.cashPledge,
      yunfei: yunfei,
      add_jf: cangetJifen
    });
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
  
  },

  liuyanInput:function(e){
    console.log("留言：" + e.detail.value);
    this.setData({
      liuyan: e.detail.value
    });
  },
  
  confirmOrder:function(){
    var that = this;
    if (that.data.agree == false) {
      wx.showModal({
        title: '提示',
        content: '请阅读并同意《家家公寓服务条款》和退订规则',
      })
    } else {
      //检查是否有房空闲
      that.getDistributionRoom(function(res){
        if(res.length==0){
          return
        }
        that.payTypeSelect();
      })
    }
  },

  getDistributionRoom: function (cb) {
    var that = this;
    // that.showModalAct();
    var fendan = this.data.goodsinfoArr[0];
    that.setData({
      fendan: fendan
    })
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "getDistributionRoom",
        "uid": that.data.cuid,
        "orgid": util.orgid,
        "timeStart": that.data.currentObjStart.getTime() / 1000,
        "timeEnd": that.data.currentObjEnd.getTime() / 1000,
        "buildingid": fendan.ghsid,
        "topicid": fendan.id
      },
      success: function (responseData) {
        console.log(responseData);
        var data = responseData.data;
        console.log("roomList", data);
        if (data && data.length > 0) {
          that.setData({
            hasData: true,
            roomList: data,
          });
          console.log("roomList", data);

          typeof cb == "function" && cb(data)
        } else {
          if (data.msg == "日期已过") {
            wx.showModal({
              title: '提示',
              content: '日期已过',
            })
          } else {
            data=[]
            that.setData({
              hasData: false,
              roomList: [],
            });
            wx.showModal({
              title: '提示',
              content: '无房可分配',
            })
            typeof cb == "function" && cb(data)
          }
        }
      }
    });
  },
  payTypeSelect: function(){
    var that = this; 

    console.log("payTypeSelect that.data.confirmOrder", that.data.confirmOrder)
    
      
    that.paygoodsAction();
   
    
   


  },

  //确认订单动作
  paygoodsAction: function(){
    var that = this;
    that.paygoodsCard();
  },

  

  //非着数皇
  paygoodsCard: function () {
    if (util.orgid != '15938' && util.orgid != '16708' && util.orgid != '12545' &&wxAuthFail) {
      app.reAuthorize(this.reGetUserInfo);
      return;
    }
    var that = this;
    var privatekey = utilMd5.hexMD5(that.data.cuid + 'wxsmallpaycarts2' + that.data.token);
    var tc = app.get_tc();
    if (!that.data.address.name) {
      app.dialog(tc == 1 ?'請添加收貨人姓名':'请添加收货人姓名', 'loading');
      return;
    }
    if (!that.data.address.phone) {
      app.dialog(tc == 1 ? '請添加聯系電話' :'请添加联系电话', 'loading');
      return;
    }
    if (!that.data.address.address) {
      app.dialog(tc == 1 ? '請添加收貨地址' :'请添加收货地址', 'loading');
      return;
    }
    if (!that.data.address.idcard) {
      app.dialog(tc == 1 ? '請添加证件号码' : '请添加证件号码', 'loading');
      return;
    }
    if(that.data.address.id){
      that.editAddress();
    }

    // that.saveAddress();
    var cartinfoArr = [];
    var pin = 0;
    for (var i = 0; i < this.data.goodsinfoArr.length; i++){
      var goodsItem = this.data.goodsinfoArr[i];
      var g_info = {};
      var dateEndObj=wx.getStorageSync("dateEndObj");
      var dateStartObj=wx.getStorageSync("dateStartObj");
      console.log("dateEndObj", dateEndObj,"||", dateEndObj.getTime())
      g_info.goods_id = goodsItem.id;
      g_info.goods_name = goodsItem.title;
      g_info.guige = goodsItem.selGuige ? goodsItem.selGuige.id : '';
      g_info.count = goodsItem.buycount;
      g_info.yunfei = goodsItem.yunfei;
      g_info.coin = goodsItem.price * goodsItem.buycount ;
      g_info.linkcode = goodsItem.linkcode;
      g_info.time_start = dateStartObj.getTime()/1000 || '';
      g_info.time_end = dateEndObj.getTime()/1000 || '';;
      cartinfoArr = cartinfoArr.concat(g_info);
      pin = (goodsItem.pin == 1 ? goodsItem.pinzong : 0);
    }
    var data = {
      'cartinfo': JSON.stringify(cartinfoArr),

      'uid': that.data.cuid,
      'type': 'goods',
      'total_fee': that.data.totalPrice+that.data.cashPledge,
      'allcoin': that.data.totalPrice * 100,
      'consignee': that.data.address.name,
      'phone': that.data.address.phone,
      'addr': that.data.address.address,
      'psd_phone': that.data.address.psd_phone ? that.data.address.psd_phone : '',
      'subject': that.data.tc == 1 ? '購買商品-批量結算' :'购买商品-批量结算' ,
      'openid': that.data.openid,
      'publickey': util.publiccode,
      'ac': "wxsmallpaycarts2",
      'privatekey': privatekey,
      'del_source': that.data.use_jf,
      'add_source': that.data.add_jf,
      'message': that.data.liuyan,
      'pin': pin,
      'ziti': that.data.ziti ? 1 : 0,
      'isdraw': payType == 2 ? 1 : 0,
      'booktime':wx.getStorageSync("booktime")||''
    };
    console.log("购物车订单参数：", data);
    // return;
    //下单请求
    util.api({
      data: data,
      method: 'POST',
      success: function (responseData) {
        var data = responseData.data;

        console.log(data);
        if (data.res === true) {
          
          if (payType == 2) {
            
            var result = that.data.tc == 1 ? '下單成功' : '下单成功';
            

            that.jindutiao(result);
            console.log("下單成功：before======clearGouwuche", data);
            if (util.orgid == 13078) {
              that.zsh_clearGouwuche();

            } else {
              that.clearGouwuche();

            }
            // app.dialogToast('下单成功', 'success', function () {
            //   wx.redirectTo({
            //     url: '/pages/order-list/order-list',
            //   });
            // });
            // that.clearGouwuche();
          } else{
            if (isTest) {
              that.paySuccess();//测试用
              return
            }
            //挂起微信支付请求
            var orderData = data.data;
            wx.requestPayment(
              {
              'timeStamp': orderData.timeStamp,
              'nonceStr': orderData.nonceStr,
              'package': orderData.package,
              'signType': orderData.signType,
              'paySign': orderData.paySign,
              'success': function (res) {
                that.paySuccess();
              },
              'fail': function (res) {
                console.log(res);
                if (res.errMsg == 'requestPayment:fail cancel') {

                } else {
                  app.dialog(that.data.tc == 1 ? '購買失敗' : '购买失败', 'loading');
                }
              }
            });
          }
            
          
        } else {
          app.dialog(that.data.tc == 1 ? '購買失敗' : '购买失败', 'loading');
        }
      }
    });
  }, 


   //支付成功后再生成订单
  setGoodsOrder: function () {
   
    var that = this;
    var privatekey = utilMd5.hexMD5(that.data.cuid + 'wxsmallpaycarts' + that.data.token);
    

    // that.saveAddress();
    var cartinfoArr = [];
    var pin = 0;
    for (var i = 0; i < this.data.goodsinfoArr.length; i++){
      var goodsItem = this.data.goodsinfoArr[i];
      var g_info = {};
      var dateEndObj=wx.getStorageSync("dateEndObj");
      var dateStartObj=wx.getStorageSync("dateStartObj");

      // var dateEndObj = new Date('2018/8/19');
      // var dateStartObj = new Date('2018/8/18');
      console.log("dateEndObj", dateEndObj,"||", dateEndObj.getTime())
      g_info.goods_id = goodsItem.id;
      g_info.goods_name = goodsItem.title;
      g_info.guige = goodsItem.selGuige ? goodsItem.selGuige.id : '';
      g_info.count = goodsItem.buycount;
      g_info.yunfei = goodsItem.yunfei;
      g_info.coin = goodsItem.price * goodsItem.buycount ;
      g_info.linkcode = goodsItem.linkcode;
      g_info.time_start = dateStartObj.getTime()/1000 || '';
      g_info.time_end = dateEndObj.getTime()/1000 || '';;
      cartinfoArr = cartinfoArr.concat(g_info);
      pin = (goodsItem.pin == 1 ? goodsItem.pinzong : 0);
    }
    var data = {
      'cartinfo': JSON.stringify(cartinfoArr),

      'uid': that.data.cuid,
      'type': 'goods',
      'total_fee': that.data.totalPrice + that.data.cashPledge,
      'allcoin': that.data.totalPrice * 100,
      'consignee': that.data.address.name,
      'phone': that.data.address.phone,
      'addr': that.data.address.address,
      'psd_phone': that.data.address.psd_phone ? that.data.address.psd_phone : '',
      'subject': that.data.tc == 1 ? '購買商品-批量結算' :'购买商品-批量结算' ,
      'openid': that.data.openid,
      'publickey': util.publiccode,
      'ac': "wxsmallpaycarts",
      'privatekey': privatekey,
      'del_source': that.data.use_jf,
      'add_source': that.data.add_jf,
      'message': that.data.liuyan,
      'pin': pin,
      'ziti': that.data.ziti ? 1 : 0,
      'isdraw': payType == 2 ? 1 : 0,
      'booktime':wx.getStorageSync("booktime")||''
    };
    console.log("购物车订单参数：", data);
    // return;
    //下单请求
    util.api({
      data: data,
      method: 'POST',
      success: function (responseData) {
        var data = responseData.data;

        console.log(data);
        if (data.res === true) {
         
            var result = that.data.tc == 1 ? '下單成功' : '下单成功';
            that.jindutiao(result);
            console.log("下單成功：before======clearGouwuche", data);
        
              that.clearGouwuche();

        
          
            
          
        } else {
          app.dialog(that.data.tc == 1 ? '購買失敗' : '购买失败', 'loading');
        }
      }
    });
  }, 


  //支付成功处理
  paySuccess: function(){
    var that =this;
    this.clearGouwuche();
    if (this.data.add_jf > 0){
      var toice = that.data.tc == 1 ? '恭喜你獲得' : "恭喜你获得 " + this.data.add_jf + that.data.tc == 1 ? '積分' :" 积分";
      wx.showModal({
        title: that.data.tc == 1 ? '支付成功' :'支付成功',
        content: toice,
        showCancel: false,
        success: function (res) {
          if (res.confirm) {
            var result = that.data.tc == 1 ? '支付成功' : '支付成功';
            // that.jindutiao(result);
            that.setGoodsOrder();
            // wx.redirectTo({
            //   url: '/pages/order-list/order-list',
            // });
          }
        }
      })
    } else {
      var result = that.data.tc == 1 ? '支付成功' :'支付成功';
      // that.jindutiao(result);
      that.setGoodsOrder();

    }
  },

  


  clearGouwuche:function(){
    if(payType == 2){
      var gwc_datas  = wx.getStorageSync('draw_datas');
    }else{
      var gwc_datas  = wx.getStorageSync('gwc_datas');
    }
    if (gwc_datas && gwc_datas.length > 0) {
      var new_gwc_datas = [];
      for (var i = 0; i < gwc_datas.length; i++) {
        var g_id = gwc_datas[i].id;
        var guige_id = gwc_datas[i].selGuige ? gwc_datas[i].selGuige.id : '';
        var notPay = true;
        for (var n = this.data.goodsinfoArr.length - 1; n >= 0; n--) {
          var pay_g_id = this.data.goodsinfoArr[n].id;
          var pay_guige_id = this.data.goodsinfoArr[n].selGuige ? this.data.goodsinfoArr[n].selGuige.id : '';
          if (g_id == pay_g_id && guige_id == pay_guige_id) {
            notPay = false;
            break;
          }
        }
        if (notPay) {
          new_gwc_datas = new_gwc_datas.concat(gwc_datas[i]);
        }
      }
      if (new_gwc_datas.length > 0) {
        if(payType == 2){
          wx.setStorageSync('draw_datas', new_gwc_datas);
        }else{
          wx.setStorageSync('gwc_datas', new_gwc_datas);
        }
        
      } else {
        if(payType == 2){
          wx.removeStorageSync("draw_datas");
        }else{
          wx.removeStorageSync("gwc_datas");
        }
        
      }
    }
  }, 

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    // this.getAddress();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
  
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
  
  },

  goAtherPage: function (e) {
    var url = e.currentTarget.dataset.link;
    wx.navigateTo({ url: url })
  },

  getWxAddress: function () {
    var that = this;
    wx.chooseAddress({
      success: function (res) {
        var addr = res.provinceName + res.cityName + res.countyName + res.detailInfo;
        that.setData({
          wx_address: res,
          address:{
            name:res.userName,
            phone:res.telNumber,
            address:addr
          }
        });
        that.saveAddress();
      },
      fail: function(){
        wx.showModal({
          title: '提示',
          content: that.data.tc == 1 ? '獲取通訊地址失敗，這將影響您的使用體驗，是否重新設置授權？' :'获取通讯地址失败，这将影响您的使用体验，是否重新设置授权？',
          showCancel: true,
          cancelText: "否",
          confirmText: "是",
          success: function (res) {
            if (res.confirm) {
              wx.OpenSetting({
                success: function (res) {
                  console.log(res);
                  console.log('success');
                  that.getWxAddress();
                },
                fail: function () {
                  console.log('fail');
                }
              })
            } else if (res.cancel) {
              console.log('用户点击否')
            }
          }
        })
      }
    })
  },

  saveAddress: function () {
    var that = this;
    var tmpmd5 = utilMd5.hexMD5(that.data.cuid + "addaddress" + that.data.token);
    console.log(' that.data.address.idcard', that.data.address.idcard)
    util.api({
      data: {
        "privatekey": tmpmd5,
        "ac": "addaddress",
        "uid": that.data.cuid,
        "name": that.data.address.name,
        "phone": that.data.address.phone,
        "address": that.data.address.address,
        "idcard": that.data.address.idcard ? that.data.address.idcard:'',
        "psd_phone": that.data.address.psd_phone ? that.data.address.psd_phone : '',
        "default": 1
      },
      method: "POST",
      success: function (responseData) {
        that.getAddress();
      }
    });
  },
  editAddress: function () {
    var that = this;
    var tmpmd5 = utilMd5.hexMD5(that.data.cuid + "editaddress" + that.data.token);
    util.api({
      data: {
        "privatekey": tmpmd5,
        "ac": "editaddress",
        "uid": that.data.cuid,
        "id": that.data.address.id,
        "name": that.data.address.name,
        "phone": that.data.address.phone,
        "address": that.data.address.address,
        "idcard": that.data.address.idcard,
        "psd_phone": that.data.address.psd_phone ? that.data.address.psd_phone : '',
        "default": 1
      },
      method: "POST",
      success: function (responseData) {
        that.getAddress();
      }
    });
  },

  delAddress: function (addrId) {
    var that = this;
    var tmpmd5 = utilMd5.hexMD5(that.data.cuid + "deladdress" + that.data.token);
    util.api({
      method: "POST",
      data: {
        "privatekey": tmpmd5,
        "ac": "deladdress",
        "uid": that.data.cuid,
        "id": addrId 
      },
      
      success: function (responseData) {
          console.log("删除地址：", responseData);
      }
    });
  },
  
  //获取运费设置
  getYunfeiSet: function () {
    var that = this;
    util.api({
      data: {
        "publickey": util.publiccode,
        "ac": "xsdyunfei",
        "binduid": util.orgid
      },
      success: function (responseData) {
        console.log("运费：", responseData);
        var data = responseData.data;
        that.setData({
          my_cion: parseInt(data.mianfei),
          set_yunfei: parseInt(data.yunfei)
        })
        that.calTotalPrice();
      }
    });
  },


  jindutiao:function(result){
    var that = this;
    that.paytuisong();
    that.setData({
      jindutiaoShow:true,
    })
    var timer = setInterval(function(){
      progressNum++;
      //当进度条为100时清除定时任务
      if (progressNum >= 100){
        clearInterval(timer);
        that.setData({
          jindutiaoTest : result,
          quedingShow: true,
        })
      }

      //并且把当前的进度值设置到progress中

      that.setData({
        progress: progressNum
      })
    },50)
  },


  //点击确定
  queding:function(e){
    var that = this;
      wx.redirectTo({
        url: '/pages/order-list/order-list',
      });
      progressNum = 0; 
  },
  //支付订单推送
  paytuisong:function(){

    var that = this;
    console.log("paytuisong")
    var tmpmd5 = utilMd5.hexMD5(that.data.cuid + "paytuisong" + that.data.token);
    util.api({
      data: {
        "privatekey": tmpmd5,
        "ac": "paytuisong",
        "uid": that.data.cuid,
        // "cartinfo": JSON.stringify(cartinfoArr),
        "binduid": util.orgid,

        'total_fee': that.data.totalPrice + that.data.cashPledge,
        'allcoin': that.data.totalPrice * 100,
        "name": that.data.address.name,
        "phone": that.data.address.phone,
        "address": that.data.address.address,
        'message': that.data.liuyan,
        "btime": that.toDate(new Date().getTime() / 1000),
        "outtime": that.toDate(new Date(1).getTime() / 1000),
        "timestart": that.data.currentObjStart.getTime()/1000,
        "timeend": that.data.currentObjEnd.getTime()/1000,
        "roomtitle": that.data.roomtitle,
      },
      method: "POST",
      success: function (responseData) {
        console.log("paytuisong===", responseData);
        // http://admin.jawanology.com/api/gzhtuisong.php?ac=tuisong&appid=wx60cf585ddbe93975&secret=24671008b1237fa9dc6458963f7891ce&binduid=18535&roomtitle=%E5%8F%8C%E4%BA%BA%E6%88%BF&timestart=1534694400&timeend=1534780800&btime=2018.08.20%2009:46&total_fee=188&name=zzz
        // http://admin.jawanology.com/api/gzhtuisong.php?ac=tuisong&appid=wx60cf585ddbe93975&secret=24671008b1237fa9dc6458963f7891ce&binduid=18535&roomtitle=体验单人大床房&timestart=1535904000&timeend=1535990400&btime=2018.09.03  16:14&phone=02081167888&total_fee=438&message=&name=zum
      }
    }); 
  },
 

  resetNavColor: function () {
    var bg_color = '#d8202d';
    var fg_color = '#ffffff';
    if (this.data.colorSet) {
      var colorJO = this.data.colorSet;
      bg_color = colorJO.titlebg;
      fg_color = colorJO.titlefont;
    }
    wx.setNavigationBarColor({
      frontColor: fg_color,
      backgroundColor: bg_color
    })

    this.setData({
      frontColor: fg_color,
      backgroundColor: bg_color
    })
  },

  

  //时间戳转换时间  
  toDate: function (number) {
    var n = number * 1000;
    var date = new Date(n);
    var Y = date.getFullYear() + '.';
    var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '.';
    var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
    var H = date.getHours() < 10 ? '0' + date.getHours() : date.getHours();
    var m = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
    console.log(Y + M + D + "  " + H + ':' + m)
    return (Y + M + D + "  " + H + ':' + m)

  },

  

  checkboxChange: function (e) {
    console.log('checkbox发生change事件，携带value值为：', e.detail.value)
    var agree = e.detail.value;
    if (agree.length==0){
      this.setData({
        agree:false
      })
      console.log('agree:false', this.data.agree)
    }else{
      this.setData({
        agree: true
      })
      console.log('agree:true', this.data.agree)
    }
  },
  // 获取AddDayCount天后的日期
  getDateStr: function (AddDayCount) {
    var dd = new Date();
    dd.setDate(dd.getDate() + AddDayCount);//获取AddDayCount天后的日期 
    var y = dd.getFullYear();
    var m = dd.getMonth() + 1;//获取当前月份的日期 
    var d = dd.getDate();
    return y + "-" + util.formatNumber(m) + "-" + util.formatNumber(d);
  },

  


  getMDstring: function (currentObj) {
    return util.formatNumber(currentObj.getMonth() + 1) + "月" + util.formatNumber(currentObj.getDate()) + "日"
  },
  
  getInterval: function () {
    var days = this.data.currentObjEnd.getTime() - this.data.currentObjStart.getTime();
    var day = Math.abs(parseInt(days / (1000 * 60 * 60 * 24)));
    this.setData({
      interval: day
    })
  },

  submitFormId: function (e) {
    app.saveFormId(e.detail.formId);
  },

})